<template>
  <view class="page">
    <!-- 导航栏 -->
    <uni-nav-bar
      title="抵用券明细"
      left-icon="left"
      :border="false"
      color="#333"
      fixed
      @clickLeft="goBack"
    />

    <view class="content">
      <!-- 剩余抵用券金额 -->
      <view class="balance-card">
        <view class="balance-label">剩余抵用券</view>
        <view class="balance-amount">
          <text class="balance-symbol">¥</text>
          <text class="balance-value">{{ remainingAmount }}</text>
        </view>
      </view>

      <!-- 筛选区域 -->
      <!-- <view class="filter-section"> -->
      <!--   <view class="filter-tabs"> -->
      <!--     <view -->
      <!--       v-for="tab in filterTabs" -->
      <!--       :key="tab.value" -->
      <!--       class="filter-tab" -->
      <!--       :class="{ active: currentFilter === tab.value }" -->
      <!--       @click="switchFilter(tab.value)" -->
      <!--     > -->
      <!--       <text class="tab-text">{{ tab.label }}</text> -->
      <!--     </view> -->
      <!--   </view> -->
      <!-- </view> -->

      <!-- 列表内容 -->
      <view class="list-content">
        <!-- 列表项 -->
        <view v-for="item in voucherList" :key="item.id" class="list-item">
          <view class="item-header">
            <view class="amount-section">
              <text class="amount-symbol">¥</text>
              <text class="amount-value">{{ item.amount }}</text>
            </view>
            <view class="status-badge" :class="getStatusClass(item.status)">
              <text class="status-text">{{ getStatusText(item.status) }}</text>
            </view>
          </view>
          <view class="item-body">
            <view class="info-row">
              <text class="info-label">券名称：</text>
              <text class="info-value">{{ item.name }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">获得时间：</text>
              <text class="info-value">{{ item.createTime }}</text>
            </view>
            <view v-if="item.useTime" class="info-row">
              <text class="info-label">使用时间：</text>
              <text class="info-value">{{ item.useTime }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">有效期：</text>
              <text class="info-value">{{ item.validTime }}</text>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="voucherList.length === 0 && !loading" class="empty-state">
          <image
            src="/static/mine/empty.png"
            class="empty-image"
            mode="aspectFit"
          />
          <text class="empty-text">暂无抵用券~</text>
        </view>

        <!-- 加载更多 -->
        <LoadMore
          v-if="voucherList.length > 0"
          :status="loadStatus"
          @retry="loadMore"
        />
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { onShow, onReachBottom } from "@dcloudio/uni-app";
import { useRequest } from "ahooks-vue";
import { encryptApi, getCouponDetails, getRemainingCoupons } from "@/api";
import { useUserStore } from "@/store/modules/user";
import { useStoreStore } from "@/store/modules/store";
import LoadMore from "@/components/common/LoadMore/LoadMore.vue";
import rsa from "@/utils/rsa";
import dayjs from "dayjs";

const userStore = useUserStore();
const storeStore = useStoreStore();

// 筛选标签
const filterTabs = ref([
  { label: "全部", value: "all" },
  { label: "未使用", value: "unused" },
  { label: "已使用", value: "used" },
  { label: "已过期", value: "expired" },
]);

// 当前筛选
const currentFilter = ref("all");

// 剩余抵用券金额
const remainingAmount = ref(0);

// 抵用券列表
const voucherList = ref([]);

// 加载状态
const hasMore = ref(true);
const page = ref(1);
const limit = ref(10);

// 加载状态文本
const loadStatus = computed(() => {
  if (couponDetailsLoading.value) return "loading";
  if (!hasMore.value) return "nomore";
  return "more";
});

// 获取剩余抵用券金额
const { run: getRemainingCouponsRun } = useRequest(
  () =>
    encryptApi({
      a_d: rsa.encrypt(
        {
          merchantId: storeStore.storeId,
          uid: userStore.userId,
        },
        true,
      ),
      a_m: "cyBerOfferIntegral/anb",
    }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("获取剩余抵用券成功:", response);
      if (response && response.data !== undefined) {
        remainingAmount.value = response.data || 0;
      }
    },
    onError: (error) => {
      console.error("获取剩余抵用券失败:", error);
    },
  },
);

// 获取抵用券列表
// const {
//   data: couponDetails,
//   loading: couponDetailsLoading,
//   run: getCouponDetailsRun,
// } = useRequest(
//   () =>
//     getCouponDetails({
//       merchantId: storeStore.storeId,
//       uid: userStore.userId,
//       limit: limit.value,
//       offset: page.value,
//     }),
//   {
//     manual: true,
//     onSuccess: (response) => {
//       console.log("获取抵用券明细成功:", response);
//       if (response && response.data) {
//         loadCouponData(response.data);
//       }
//     },
//     onError: (error) => {
//       console.error("获取抵用券明细失败:", error);
//       uni.showToast({
//         title: "获取数据失败",
//         icon: "none",
//       });
//     },
//   },
// );

const {
  data: couponDetails,
  loading: couponDetailsLoading,
  run: getCouponDetailsRun,
} = useRequest(
  () =>
    encryptApi({
      a_d: rsa.encrypt(
        {
          merchantId: storeStore.storeId,
          uid: userStore.userId,
          limit: limit.value,
          offset: page.value,
        },
        true,
      ),
      a_m: "cyBerIntegral_bna",
    }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("获取抵用券明细成功:", response);
      if (response && response.data) {
        loadCouponData(response.data);
      }
    },
    onError: (error) => {
      console.error("获取抵用券明细失败:", error);
      uni.showToast({
        title: "获取数据失败",
        icon: "none",
      });
    },
  },
);

// 加载抵用券数据
const loadCouponData = (data) => {
  console.log("抵用券数据:", data);

  // 接口返回格式：{ total: 6, rows: [...] }
  const rows = data?.rows || [];

  if (Array.isArray(rows) && rows.length > 0) {
    const mappedData = rows.map((item, index) => ({
      id: item.id || `${Date.now()}_${index}`,
      amount: item.money || 0,
      name: item.context || "抵用券",
      createTime: item.time
        ? dayjs(item.time).format("YYYY-MM-DD HH:mm:ss")
        : "",
      useTime:
        item.status === 0
          ? item.time
            ? dayjs(item.time).format("YYYY-MM-DD HH:mm:ss")
            : ""
          : "",
      validTime: item.validTime || "长期有效",
      status: item.status, // 0:已使用(减少) 1:未使用(增加)
    }));

    // 第一页替换，其他页追加
    if (page.value === 1) {
      voucherList.value = mappedData;
    } else {
      voucherList.value = [...voucherList.value, ...mappedData];
    }

    // 判断是否还有更多数据
    hasMore.value = mappedData.length >= limit.value;
  } else {
    // 如果不是数组或没有数据
    if (page.value === 1) {
      voucherList.value = [];
    }
    hasMore.value = false;
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 切换筛选
const switchFilter = (value) => {
  currentFilter.value = value;
  refreshData();
};

// 刷新数据
const refreshData = () => {
  page.value = 1;
  voucherList.value = [];
  hasMore.value = true;
  loadData();
};

// 加载数据
const loadData = () => {
  if (couponDetailsLoading.value) return;

  console.log("加载抵用券数据", {
    filter: currentFilter.value,
    page: page.value,
    limit: limit.value,
  });

  getCouponDetailsRun();
};

// 加载更多
const loadMore = () => {
  if (couponDetailsLoading.value || !hasMore.value) return;
  page.value += 1;
  loadData();
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0:
      return "已使用"; // 减少（使用）
    case 1:
      return "未使用"; // 增加（获得）
    default:
      return "未知";
  }
};

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 0:
      return "status-used"; // 已使用
    case 1:
      return "status-unused"; // 未使用
    default:
      return "";
  }
};

// 页面显示时刷新数据（包括切换店铺后返回）
onShow(() => {
  console.log("抵用券明细页面显示");
  getRemainingCouponsRun(); // 获取剩余金额
  refreshData();
});

// 页面触底事件
onReachBottom(() => {
  loadMore();
});
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.content {
  padding: 20rpx 32rpx;
}

// 剩余金额卡片
.balance-card {
  background: linear-gradient(135deg, #fabc02 0%, #ffd54f 100%);
  border-radius: 16rpx;
  padding: 40rpx 32rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 8rpx 24rpx rgba(250, 188, 2, 0.2);
}

.balance-label {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 16rpx;
}

.balance-amount {
  display: flex;
  align-items: baseline;
}

.balance-symbol {
  font-size: 40rpx;
  color: #fff;
  font-weight: 600;
  margin-right: 8rpx;
}

.balance-value {
  font-size: 64rpx;
  color: #fff;
  font-weight: 700;
  line-height: 1;
}

// 筛选区域
.filter-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.filter-tabs {
  display: flex;
  gap: 16rpx;
}

.filter-tab {
  flex: 1;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
  background-color: #f5f5f5;
  transition: all 0.3s;

  &:active {
    opacity: 0.8;
  }

  &.active {
    background-color: #fabc02;

    .tab-text {
      color: #fff;
      font-weight: 600;
    }
  }
}

.tab-text {
  font-size: 28rpx;
  color: #333;
}

// 列表内容
.list-content {
  min-height: 400rpx;
}

.list-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 32rpx;
  margin-bottom: 20rpx;

  &:active {
    opacity: 0.9;
  }
}

.item-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
  margin-bottom: 24rpx;
}

.amount-section {
  display: flex;
  align-items: baseline;
}

.amount-symbol {
  font-size: 32rpx;
  color: #fabc02;
  font-weight: 600;
  margin-right: 4rpx;
}

.amount-value {
  font-size: 48rpx;
  color: #fabc02;
  font-weight: 600;
}

.status-badge {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;

  &.status-unused {
    background-color: #e8f5e9;

    .status-text {
      color: #4caf50;
    }
  }

  &.status-used {
    background-color: #f5f5f5;

    .status-text {
      color: #999;
    }
  }

  &.status-expired {
    background-color: #ffebee;

    .status-text {
      color: #f44336;
    }
  }
}

.status-text {
  font-size: 24rpx;
  font-weight: 500;
}

.item-body {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.info-row {
  display: flex;
  align-items: center;
}

.info-label {
  font-size: 28rpx;
  color: #666;
  min-width: 140rpx;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.empty-image {
  width: 300rpx;
  height: 300rpx;
  margin-bottom: 32rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style>
